package boot.spring.service.impl;

import boot.spring.mapper.IntersectionMapper;
import boot.spring.model.entity.Intersection;
import boot.spring.service.IntersectionService;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKTWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IntersectionServiceImpl implements IntersectionService {

    @Autowired
    private IntersectionMapper intersectionMapper;

    private final GeometryFactory geometryFactory = new GeometryFactory();
    private final WKTWriter wktWriter = new WKTWriter();

    /**
     * 根据矩形范围查询路口
     *
     * @param minX 最小经度
     * @param minY 最小纬度
     * @param maxX 最大经度
     * @param maxY 最大纬度
     * @return 范围内的路口列表
     */
    public List<Intersection> getIntersectionsByBbox(double minX, double minY, double maxX, double maxY) {
        Coordinate[] coordinates = new Coordinate[]{
                new Coordinate(minX, minY),
                new Coordinate(maxX, minY),
                new Coordinate(maxX, maxY),
                new Coordinate(minX, maxY),
                new Coordinate(minX, minY)
        };
        Polygon bbox = geometryFactory.createPolygon(coordinates);
        String wkt = wktWriter.write(bbox);
        return intersectionMapper.findIntersectionsWithin(wkt);
    }

    /**
     * 根据点和半径查询附近路口
     *
     * @param lng    经度
     * @param lat    纬度
     * @param radius 半径(米)
     * @return 附近的路口列表
     */
    public List<Intersection> getNearbyIntersections(double lng, double lat, double radius) {
        Point point = geometryFactory.createPoint(new Coordinate(lng, lat));
        String wkt = wktWriter.write(point);
        return intersectionMapper.findIntersectionsNearby(wkt, radius);
    }

    /**
     * 根据多边形WKT查询路口
     *
     * @param polygonWkt 多边形WKT字符串
     * @return 多边形内的路口列表
     */
    public List<Intersection> getIntersectionsByPolygon(String polygonWkt) {
        return intersectionMapper.findIntersectionsByPolygon(polygonWkt);
    }
}